package org.dromara.rocketmq.demo.consumer;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.cloud.alarm.dinger.core.entity.DingerRequest;
import com.cloud.alarm.dinger.core.entity.enums.MessageSubType;
import com.cloud.rocketmq.base.entity.ConsumeFailMessage;
import com.cloud.rocketmq.base.utils.JsonUtil;
import com.cloud.rocketmq.spring.core.ConsumeFailureStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.alarm.utils.AlarmUtil;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Objects;

/**
 * @author: zhou shuai
 * @date: 2024/6/2 10:55
 * @version: v1
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WeTalkConsumeFailureStrategy implements ConsumeFailureStrategy {

    /**
     * 消费失败机器人告警
     *
     * @author: zhou shuai
     * @date: 2024/6/2 10:56
     * @param: consumeFailMessage
     */
    @Override
    public void onConsumeFailure(ConsumeFailMessage consumeFailMessage) {
        log.info("consumeFailMessage is {}", JsonUtil.toString(consumeFailMessage));
        String title = "RocketMQ消费失败";
        StringBuilder mdBuilder = new StringBuilder();
        String titleContent = StrUtil.format("<font color=\"warning\">【{}】</font>Topic消费失败,请相关同事注意.\n相关参数如下:\n", consumeFailMessage.getTopic());

        mdBuilder.append(titleContent);
        Field[] fields = ReflectUtil.getFields(consumeFailMessage.getClass());
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            String fieldName = field.getName();
            Object fieldValue = ReflectUtil.getFieldValue(consumeFailMessage, field);
            if (Objects.isNull(fieldValue)) {
                continue;
            }
            String fieldContent = StrUtil.format(">**{}:** <font color=\"comment\">{}</font> \n", fieldName, fieldValue);
            mdBuilder.append(fieldContent);
        }
        DingerRequest dingerRequest = DingerRequest.request(mdBuilder.toString(), title, List.of("17756228281"));
        AlarmUtil.send(MessageSubType.MARKDOWN, dingerRequest);
    }

}
